package com.qidian.util.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Author: 戴着假发的程序员
 * Date: 2024-04-17 15:00
 * company: 起点编程
 **/

public class RequestTimeHandlerInterceptor implements HandlerInterceptor {
    private ThreadLocal<Long> tl = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 记录时间
        tl.set(System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 再次记录时间，并且计算时间
        long time = System.currentTimeMillis() - tl.get();
        // 获取请求的url
        String url = request.getRequestURI();
        System.out.println("请求[" + url + "] 耗时 " + time + " ms" );
    }
}
